# -*- coding: UTF-8 -*-
# @Time : 2021-01-01 21:16
# @File : LogUtil.py
import logging
import os
import time
from config import Conf

# 定义日志级别的映射
loglevel = {
    "info": logging.INFO,
    "debug": logging.DEBUG,
    "warning": logging.WARNING,
    "error": logging.ERROR
}


# 1、创建类
class Logger:
    # 2、定义参数
    def __init__(self, log_file, log_name, log_level):
        self.log_file = log_file
        self.log_name = log_name
        self.log_level = log_level
        # 3、编写输出控制台或文件
        # 1、设置logger名称
        self.logger = logging.getLogger(self.log_name)
        # 2、设置logger级别
        self.logger.setLevel(loglevel[self.log_level])

        # 3、创建输出控制台handler
        if not self.logger.handlers:
            fh_stream = logging.StreamHandler()
            fh_stream.setLevel(loglevel[self.log_level])
            formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s ')
            fh_stream.setFormatter(formatter)
            self.logger.addHandler(fh_stream)
            # 输出日志文件
            fh_file = logging.FileHandler(self.log_file)
            fh_file.setLevel(loglevel[self.log_level])
            fh_file.setFormatter(formatter)
            # 6、添加handler
            self.logger.addHandler(fh_file)


# 1、初始化参数日志
# 日志文件名称 = logs目录 + 当前时间 + 扩展ming
log_path = Conf.get_config_logs()
current_time = time.strftime("%Y-%m-%d", time.localtime())
log_extension = '.log'
logfile = os.path.join(log_path, log_path + os.sep + current_time + log_extension)
# print(logfile)
# 日志级别
log = 'debug'


# 2、对外方法，初始化log工具，提供其他类使用
def my_log(log_name=__file__):
    return Logger(logfile, log_name, log, ).logger


if __name__ == '__main__':
    log = my_log('test_demo')
    log.info('info')
    log.error('error')
